{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Azure AI Foundry Agent\n",
    "\n",
    "In AutoGen, you can build and deploy agents that are backed by the [Azure AI Foundry Agent Service](https://learn.microsoft.com/en-us/azure/ai-services/agents/overview) using the {py:class}`~autogen_ext.agents.azure._azure_ai_agent.AzureAIAgent` class. Here, important aspects of the agent including the provisioned model, tools (e.g, code interpreter, bing search grounding, file search etc.), observability, and security are managed by Azure. This allows you to focus on building your agent without worrying about the underlying infrastructure.\n",
    "\n",
    "In this guide, we will explore an example of creating an Azure AI Foundry Agent using the `AzureAIAgent` that can address tasks using the Azure Grounding with Bing Search tool."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# pip install \"autogen-ext[azure]\"  # For Azure AI Foundry Agent Service"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Bing Search Grounding \n",
    "\n",
    "An {py:class}`~autogen_ext.agents.azure._azure_ai_agent.AzureAIAgent` can be assigned a set of tools including [Grounding with Bing Search](https://learn.microsoft.com/en-us/azure/ai-services/agents/how-to/tools/bing-grounding?tabs=python&pivots=overview#setup). \n",
    "\n",
    "Grounding with Bing Search allows your Azure AI Agents to incorporate real-time public web data when generating responses. You need to create a Grounding with Bing Search resource, and then connect this resource to your Azure AI Agents. When a user sends a query, Azure AI Agents decide if Grounding with Bing Search should be leveraged or not. If so, it will leverage Bing to search over public web data and return relevant chunks. Lastly, Azure AI Agents will use returned chunks to generate a response.\n",
    "\n",
    "## Prerequisites\n",
    "\n",
    "- You need to have an Azure subscription.\n",
    "- You need to have the Azure CLI installed and configured. (also login using the command `az login` to enable default credentials)\n",
    "- You need to have the `autogen-ext[azure]` package installed.\n",
    "\n",
    "You can create a [Grounding with Bing Search resource in the Azure portal](https://portal.azure.com/#create/Microsoft.BingGroundingSearch). Note that you will need to have owner or contributor role in your subscription or resource group to create it. Once you have created your resource, you can then pass it to the Azure Foundry Agent using the resource name.\n",
    "\n",
    "In the following example, we will create a new Azure Foundry Agent that uses the Grounding with Bing Search resource.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "import dotenv\n",
    "from autogen_agentchat.messages import TextMessage\n",
    "from autogen_core import CancellationToken\n",
    "from autogen_ext.agents.azure import AzureAIAgent\n",
    "from azure.ai.agents.models import BingGroundingTool\n",
    "from azure.ai.projects.aio import AIProjectClient\n",
    "from azure.identity.aio import DefaultAzureCredential\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "\n",
    "async def bing_example() -> None:\n",
    "    async with DefaultAzureCredential() as credential:  # type: ignore\n",
    "        async with AIProjectClient(  # type: ignore\n",
    "            credential=credential, endpoint=os.getenv(\"AZURE_PROJECT_ENDPOINT\", \"\")\n",
    "        ) as project_client:\n",
    "            conn = await project_client.connections.get(name=os.getenv(\"BING_CONNECTION_NAME\", \"\"))\n",
    "\n",
    "            bing_tool = BingGroundingTool(conn.id)\n",
    "            agent_with_bing_grounding = AzureAIAgent(\n",
    "                name=\"bing_agent\",\n",
    "                description=\"An AI assistant with Bing grounding\",\n",
    "                project_client=project_client,\n",
    "                deployment_name=\"gpt-4o\",\n",
    "                instructions=\"You are a helpful assistant.\",\n",
    "                tools=bing_tool.definitions,\n",
    "                metadata={\"source\": \"AzureAIAgent\"},\n",
    "            )\n",
    "\n",
    "            # For the bing grounding tool to return the citations, the message must contain an instruction for the model to do return them.\n",
    "            # For example: \"Please provide citations for the answers\"\n",
    "\n",
    "            result = await agent_with_bing_grounding.on_messages(\n",
    "                messages=[\n",
    "                    TextMessage(\n",
    "                        content=\"What is Microsoft's annual leave policy? Provide citations for your answers.\",\n",
    "                        source=\"user\",\n",
    "                    )\n",
    "                ],\n",
    "                cancellation_token=CancellationToken(),\n",
    "                message_limit=5,\n",
    "            )\n",
    "            print(result)\n",
    "\n",
    "\n",
    "await bing_example()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that you can also provide other Azure Backed [tools](https://learn.microsoft.com/en-us/azure/ai-services/agents/how-to/tools/overview) and local client side functions to the agent.\n",
    "\n",
    "See the {py:class}`~autogen_ext.agents.azure._azure_ai_agent.AzureAIAgent` class api documentation for more details on how to create an Azure Foundry Agent."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
